<?php
require_once 'include/inc.config.php';
require_once WACT_ROOT . '/db/db.inc.php';
require_once APP_ROOT.'model/common/utils.php';
require_once APP_ROOT.'model/common/session.php';
require_once APP_ROOT.'model/common/date.php';
require_once APP_ROOT.'model/common/parameters.php';
require_once APP_ROOT.'model/common/site.php';
require_once APP_ROOT.'model/common/statdivisions.php';



class StatTeam {


    function insertTeam(&$data) {
    	$site_id = Site::getSiteID();
    	$data->set('site_id',$site_id);
    	$enabled = $data->get('enabled');
    	if (!$enabled) $data->set('enabled',0);

    	$tz =& new MyTimeZone();
        $data->set('date_added', gmdate("Y-m-d H:i", $tz->timeNowLocal() ) );

        $Record =& DBC::NewRecord($data);
       return $Record->insertId('sport_stat_teams',
            array('site_id','divisionID', 'enabled', 'date_added', 'teamName'), 'teamID');
    }



    function &getRecord($id) {
        return DBC::FindRecord("SELECT T.*, D.divisionName, L.leagueName
        FROM sport_stat_teams T
        left outer join sport_stat_divisions D on T.divisionID = D.divisionID
        left outer join sport_stat_leagues L
    	on D.leagueID = L.leagueID
     	WHERE T.teamID = ". DBC::makeLiteral($id));
    }

    function updateTeam($id, &$data) {
        $site_id = Site::getSiteID();
    	$data->set('site_id',$site_id);

    	$enabled = $data->get('enabled');
    	if (!$enabled) $data->set('enabled',0);

        $Record =& DBC::NewRecord($data);
        $Record->update('sport_stat_teams',
            array('site_id','divisionID', 'enabled', 'teamName'),
            "teamID=". DBC::makeLiteral($id));
    }

    function updateTeamStats($id, &$data) {
        $site_id = Site::getSiteID();
    	$data->set('site_id',$site_id);

    	$enabled = $data->get('enabled');
    	if (!$enabled) $data->set('enabled',0);

        $Record =& DBC::NewRecord($data);
        $Record->update('sport_stat_teams',
            array('wins','losses', 'ties', 'pct'),
            "teamID=". DBC::makeLiteral($id));
    }

    function calculateTeamStats($teamID) {

		$ds =& new DataSpace();
        $wins = Score::getTeamWins($teamID);
        $losses = Score::getTeamLosses($teamID);
        $ties = Score::getTeamTies($teamID);
    	$ds->set('wins',$wins);
    	$ds->set('losses',$losses);
    	$ds->set('ties',$ties);

    	$pct = ($wins + $ties/2.0) / ($wins + $ties + $losses);
    	//print "team ID = ".$teamID.'------PCT = '.$pct;
    	$ds->set('pct',$pct);

    	StatTeam::updateTeamStats($teamID, $ds);

    }







    function denyTeam($team_id) {
        $data = new DataSpace();
        $data->set('enabled',0);

		$Record =& DBC::NewRecord($data);
        $Record->update('sport_stat_teams', array('enabled'),
            "teamID=". DBC::makeLiteral($team_id));
    }

    function publishTeam($team_id) {
        $data = new DataSpace();
        $data->set('enabled',1);

    	$Record =& DBC::NewRecord($data);
        $Record->update('sport_stat_teams',
            array('enabled'), "teamID=". DBC::makeLiteral($team_id));
    }


	function delete($id) {
        DBC::execute("DELETE FROM sport_stat_teams WHERE teamID=". DBC::makeLiteral($id));
    }

    function &getTeamsList(&$Pager, &$request, &$responseModel,$options=null, $onlynew=false) {
        $site_id = Site::getSiteID();
     	//restore filter from session
     	Session::loadResponseModel($responseModel,'filter.statteams');
     	$sql = "select T.*, D.divisionName, L.leagueName
     		from sport_stat_teams T
     		left outer join sport_stat_divisions D
     		on T.divisionID = D.divisionID
     		left outer join sport_stat_leagues L
     		on D.leagueID = L.leagueID
     		";

     	if($options==null){
     		if ($onlynew) {
                $sql.=" where 1=1 and (T.enabled=0 or T.enabled is null)
                and T.site_id = ".DBC::makeLiteral($site_id)." ".StatTeam::getTeamsFilter($request, $responseModel)."
     		 	order by T.pct desc, T.wins desc, L.leagueName, D.divisionName, T.divisionID, T.teamName, T.date_added desc ";
     		} else {
     			$sql.=" where 1=1
                and T.site_id = ".DBC::makeLiteral($site_id)." ".StatTeam::getTeamsFilter($request, $responseModel)."
     		 	order by ".StatTeam::getTeamsOrder($request, $responseModel);
     		}
            //print $sql;
        	return DBC::NewPagedRecordSet($sql, $Pager);
     	}else{
     		$sql.=" where 1=1
             and T.site_id = ".DBC::makeLiteral($site_id);
     		$sql.=" order by T.pct desc, T.wins desc, L.leagueName, D.divisionName, T.divisionID, T.teamName, T.date_added desc  ";
     		error_log("[SQL:]$sql");
     		//print $sql;
     		return DBC::NewPagedRecordSet($sql, $Pager);
     	}
     }

     function getTeamsFilter(&$request,&$responseModel) {
      	$where = '';
      	$filter_team_id = $responseModel->get('filter_team_id');
        $team_id = $responseModel->get('team_id');
      	if ($filter_team_id)  $where .= ' and T.teamID = '.DBC::makeLiteral($team_id);

      	$filter_division_id = $responseModel->get('filter_division_id');
        $division_id = $responseModel->get('division_id');
      	if ($filter_division_id)  $where .= ' and D.divisionID = '.DBC::makeLiteral($division_id);

        $filter_title = $responseModel->get('filter_title');
        $title = $responseModel->get('title');
        if ($filter_title)  $where .= ' and T.teamName like '.DBC::makeLiteral('%'.$title.'%').'  ';




        return $where;
      }

      function getTeamsOrder(&$request,&$responseModel) {
      	$sortby = ' T.pct desc, T.wins desc, L.leagueName, D.divisionName, T.divisionID, T.teamName, T.date_added desc';
      	$sortby = $responseModel->get('sort');
      	if ($sortby) return $sortby;
      	else return ' T.pct desc, T.wins desc, L.leagueName, D.divisionName, T.divisionID, T.teamName, T.date_added desc';
      }


      function &getNewTeamsList(&$Pager, &$request, &$responseModel) {
      	return StatTeam::getTeamsList($Pager, $request, $responseModel,null,true);
      }



     function &getTeamsPublic($divisionID) {
        $site_id = Site::getSiteID();
        if (!$divisionID) $divisionID=Division::getFirstDivisionID();
		$sql = "select T.*, D.divisionName, L.leagueName
     		from sport_stat_teams T
     		left outer join sport_stat_divisions D
     		on T.divisionID = D.divisionID
     		left outer join sport_stat_leagues L
     		on D.leagueID = L.leagueID
     		where T.enabled = 1 ";

     	if ($divisionID) $sql.=" and T.divisionID = $divisionID";
     	$sql.=" and T.site_id = ".DBC::makeLiteral($site_id);
        $sql.=" order by T.pct desc, T.wins desc, D.divisionName, T.divisionID, T.teamName, T.date_added desc ";
     	//print  $sql;
        $rs =& DBC::NewRecordSet($sql);


        return $rs;
     }

     //get the array of teams for list
	function &getTeamsForList() {
		$site_id = Site::getSiteID();
		$sql = "select T.*, D.divisionName, L.leagueName    from sport_stat_teams T ";
		$sql .= " inner join sport_stat_divisions D on T.divisionID = D.divisionID
		left outer join sport_stat_leagues L
  		on D.leagueID = L.leagueID";

        $sql .= " where T.site_id =  ".DBC::makeLiteral($site_id);
        $sql.=" order by L.leagueName, D.divisionName, T.teamName ";
		$result =& DBC::NewRecordSet($sql);
		$result->reset();
		//$i=1;
        $teams=array();

        while($result->next()) {
        		$id =  $result->get('teamID');
        		$teamName = $result->get('teamName');
                $divisionName = $result->get('divisionName');
                $leagueName = $result->get('leagueName');
                if ($leagueName)
                	$teams[$id]= $leagueName.' - '.$divisionName.' - '.$teamName;
                else
                	$teams[$id]= $divisionName.' - '.$teamName;
        }
        return $teams;
	}

	function &getSeasonYears(){

    	$years = array();

    	$i = 2007;
    	while ($i<=2099) {
        	$years[$i]=$i;
        	$i++;
        }
        return $years;
    }

    function AreTeamsInDivision($team1ID, $team2ID) {

			$sql = " select T1.* from sport_stat_teams T1
			inner join sport_stat_divisions D on T1.divisionID = D.divisionID
			inner join sport_stat_teams T2 on T2.divisionID = D.divisionID
            where T1.teamID = ".DBC::makeLiteral($team1ID)." and T2.teamID = ".DBC::makeLiteral($team2ID);

			//error_log("[TRABLA]$sql");
			$rs =& DBC::NewRecordSet($sql);
			//print_r($rs);
			$rs->reset();
			if (!$rs->next()) { //print 'Not Linked!';
				return false;
			}
			else {
				//print 'Linked!';
				return true;
			}
	}






}

?>
